<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getAttractionDetail, addAttractionReview } from "@/api/tourism";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Star,
  Location,
  PriceTag,
  Picture,
  Delete,
} from "@element-plus/icons-vue";
import request from "@/utils/request";

interface Review {
  id: number;
  attractionId: number;
  userId: number;
  comment: string;
  rating: number;
  createdBy: string;
  createdTime: string;
  updateBy: string | null;
  updateTime: string | null;
  userName: string;
  userAvatar: string | null;
}

interface AttractionDetail {
  id: number;
  name: string;
  description: string;
  supplierId: number;
  price: number;
  type: number;
  rating: number;
  createdBy: string;
  createdTime: string;
  updateBy: string;
  updateTime: string;
  avatar: string | null;
  attractionReviewsRespList: Review[];
}

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const attraction = ref<AttractionDetail | null>(null);

// 获取当前用户ID
const currentUserId = ref<number>(0);

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    const res = await request({
      url: "/user/tourist/queryInfo",
      method: "get",
    });
    if (res.success) {
      currentUserId.value = res.data.id;
    }
  } catch (error) {
    console.error("获取用户信息失败：", error);
  }
};

// 获取景点详情
const fetchAttractionDetail = async () => {
  try {
    const id = Array.isArray(route.params.id)
      ? route.params.id[0]
      : route.params.id;
    const res = await getAttractionDetail(id);
    if (res.success) {
      attraction.value = res.data;
    } else {
      ElMessage.error(res.message || "获取景点详情失败");
    }
  } catch (error) {
    console.error("获取景点详情失败:", error);
    ElMessage.error("获取景点详情失败");
  }
};

// 获取景点类型文本
const getTypeText = (type: number) => {
  const typeMap = {
    1: "农家乐",
    2: "采摘园",
    3: "观光园",
    // 可以根据实际类型继续添加
  };
  return typeMap[type as keyof typeof typeMap] || "其他";
};

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
};

// 评论表单数据
const commentForm = ref({
  rating: 5,
  comment: "",
});

// 提交评论
const handleSubmitComment = async () => {
  if (!commentForm.value.comment.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  try {
    const res = await addAttractionReview({
      attractionId: Number(route.params.id),
      comment: commentForm.value.comment,
      rating: commentForm.value.rating,
    });

    if (res.success) {
      ElMessage.success("评论发表成功");
      // 重置表单
      commentForm.value.comment = "";
      commentForm.value.rating = 5;
      // 重新获取详情数据以更新评论列表
      await fetchAttractionDetail();
    } else {
      // 处理失败情况，显示后端返回的错误信息
      ElMessage.error(res.message || "评论发表失败");
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("评论发表失败，请稍后重试");
  }
};

// 删除评论
const handleDeleteComment = async (commentId: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await request({
      url: "/attractionReviews/deleteById",
      method: "post",
      data: {
        id: commentId,
      },
    });

    if (res.success) {
      ElMessage.success("删除成功");
      // 重新获取景点详情以更新评论列表
      await fetchAttractionDetail();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

onMounted(() => {
  if (!route.params.id) {
    ElMessage.error("景点ID不存在");
    router.push("/tourist/tourism");
    return;
  }
  getCurrentUser(); // 获取当前用户信息
  fetchAttractionDetail();
});
</script>

<template>
  <div class="attraction-detail" v-loading="loading">
    <el-card v-if="attraction" class="detail-card">
      <div class="attraction-image">
        <el-image :src="attraction.avatar" fit="cover" class="main-image">
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
              <span>暂无图片</span>
            </div>
          </template>
        </el-image>
      </div>

      <div class="header">
        <h1>{{ attraction.name }}</h1>
        <div class="rating">
          <el-rate
            v-model="attraction.rating"
            disabled
            show-score
            text-color="#ff9900"
          />
        </div>
      </div>

      <div class="info-section">
        <div class="type-tag">
          <el-tag type="success">{{ getTypeText(attraction.type) }}</el-tag>
        </div>
        <div class="price">
          <el-icon><PriceTag /></el-icon>
          <span>¥{{ attraction.price }}/人</span>
        </div>
      </div>

      <div class="description">
        {{ attraction.description }}
      </div>

      <!-- 评论区域 -->
      <div class="reviews-section">
        <h2>游客评价</h2>

        <!-- 发表评论 -->
        <div class="comment-form">
          <el-card class="form-card">
            <h3>发表评论</h3>
            <div class="rating-input">
              <span class="label">评分：</span>
              <el-rate
                v-model="commentForm.rating"
                :max="5"
                :allow-half="true"
                show-score
              />
            </div>
            <div class="comment-input">
              <el-input
                v-model="commentForm.comment"
                type="textarea"
                :rows="3"
                placeholder="请分享您的游玩体验..."
                maxlength="200"
                show-word-limit
              />
            </div>
            <div class="form-footer">
              <el-button
                type="primary"
                @click="handleSubmitComment"
                :disabled="!commentForm.comment.trim()"
              >
                发表评论
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 评论列表 -->
        <div class="reviews-list">
          <el-empty
            v-if="!attraction.attractionReviewsRespList.length"
            description="暂无评价"
          />

          <el-card
            v-for="review in attraction.attractionReviewsRespList"
            :key="review.id"
            class="review-card"
          >
            <div class="review-header">
              <div class="user-info">
                <el-avatar :size="40" :src="review.userAvatar">
                  {{ review.userName?.charAt(0)?.toUpperCase() }}
                </el-avatar>
                <span class="user-name">{{ review.userName }}</span>
              </div>
              <div class="review-actions">
                <el-rate
                  v-model="review.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
                <!-- 只有当评论是当前用户发的才显示删除按钮 -->
                <el-button
                  v-if="review.userId === currentUserId"
                  type="danger"
                  link
                  @click="handleDeleteComment(review.id)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
            <div class="review-content">
              {{ review.comment }}
            </div>
            <div class="review-footer">
              <span class="review-time">{{
                formatDate(review.createdTime)
              }}</span>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.attraction-detail {
  padding: 20px;
}

.detail-card {
  max-width: 1200px;
  margin: 0 auto;
}

.attraction-image {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 400px;
  background: #f5f7fa;
  color: #909399;
}

.image-slot .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.info-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.price {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.description {
  font-size: 16px;
  line-height: 1.6;
  color: #606266;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.reviews-section {
  margin-top: 40px;
}

h2 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #303133;
}

.reviews-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-card {
  margin-bottom: 15px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-name {
  font-weight: bold;
  color: #303133;
}

.review-content {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  margin: 10px 0;
}

.review-footer {
  color: #909399;
  font-size: 12px;
}

.review-time {
  color: #909399;
}

.comment-form {
  margin-bottom: 30px;
}

.form-card {
  background-color: #f8f9fa;
}

.form-card h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

.rating-input {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.rating-input .label {
  margin-right: 10px;
  color: #606266;
}

.comment-input {
  margin-bottom: 15px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-rate) {
  display: inline-flex;
  align-items: center;
}

:deep(.el-rate__text) {
  color: #ff9900;
}
</style> 